package java复习202407;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class c9_反射验证 {

    @Test
    public void 获取Class类对象的三种方式(){
        Class<String> strClass1 = String.class;

        String str = new String("1");
        Class<? extends String> strClass2 = str.getClass();

        try {
            Class<?> strClass3 = Class.forName("java.lang.String");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    class User{
        String name;
        List<成绩> 成绩;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<c9_反射验证.成绩> get成绩() {
            return 成绩;
        }

        public void set成绩(List<c9_反射验证.成绩> 成绩) {
            this.成绩 = 成绩;
        }
    }

    class 成绩{
        String time;
        String kemu;
        String fenshu;

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public String getKemu() {
            return kemu;
        }

        public void setKemu(String kemu) {
            this.kemu = kemu;
        }

        public String getFenshu() {
            return fenshu;
        }

        public void setFenshu(String fenshu) {
            this.fenshu = fenshu;
        }
    }

    @Test
    public void 反射获取字段列表验证(){
        User user = new User();
        ArrayList<成绩> 成绩s = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            成绩 成绩 = new 成绩();
            成绩.setTime(i+"");
            成绩.setKemu("科目"+i);
            成绩.setFenshu(60+i+"分");
            成绩s.add(成绩);
        }
        user.set成绩(成绩s);
        user.setName("张三");

        ArrayList<Field> fields = new ArrayList<>();
        Object objUser = user;
        Class userClass = objUser.getClass();
        Field[] declaredFields = userClass.getDeclaredFields();
        System.out.println(declaredFields);
        while (userClass != null){
            fields.addAll(0, Arrays.asList(userClass.getDeclaredFields()));
            userClass = userClass.getSuperclass();
        }
        System.out.println(fields);
    }

    @Test
    public void 验证类型(){
        User user = new User();
        Object userObj = (Object) user;
        System.out.println(userObj instanceof User);
//        checkClassType(userObj); // 类型不同无法使用该参数

    }

    public void checkClassType(User user){
        System.out.println(user);
    }
}
